<?php
// 应用公共文件

use app\admin\model\auth\Permissions;
use app\admin\model\auth\RolePermissions;
use app\admin\model\auth\Roles;

if(!function_exists('get_weeks')){
    /**
     * 获取最近七天所有日期
     */
    function get_weeks($time = '', $format='Y-m-d'){
        $time = $time != '' ? $time : time();
        //组合数据
        $date = [];
        for ($i=1; $i<=7; $i++){
            $date[$i] = date($format ,strtotime( '+' . ($i-7) .' days', $time));
        }
        return $date;
    }
}

if (!function_exists('get_rand_mobile')) {

    /**

     * 添加不重复手机信息

     */

    function get_rand_mobile()

    {
        $obj = new \app\admin\model\member\Member();
        $arr = array(
            130, 131, 132, 133, 134, 135, 136, 137, 138, 139,

            144, 147,

            150, 151, 152, 153, 155, 156, 157, 158, 159,

            176, 177, 178,

            180, 181, 182, 183, 184, 185, 186, 187, 188, 189,

        );
        $mobile = $arr[array_rand($arr)] . mt_rand(1000, 9999) . mt_rand(1000, 9999);

        $res = $obj->where(['phone' => $mobile])->find();
        if ($res) {
            get_rand_mobile();

        } else {
            return $mobile;
        }

    }

}


if (!function_exists('get_rand_email')) {

    /**
     * 添加不重复邮箱信息
     */
    function get_rand_email()

    {
        $obj = new \app\admin\model\member\Member();
        $arr = array(
            130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
            144, 147,
            150, 151, 152, 153, 155, 156, 157, 158, 159,
            176, 177, 178,
            180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
        );
        $ext=['@163.com','@qq.com'];
        $email = $arr[array_rand($arr)] . mt_rand(1000, 9999) . mt_rand(1000, 9999) .$ext[array_rand($ext)];

        $res = $obj->where(['email' => $email])->find();
        if ($res) {
            get_rand_email();
        } else {

            return $email;
        }
    }

}



if (!function_exists('get_app_id')) {

    /**
     * 添加不重复API信息
     */

    function get_app_id()
    {

       $MemberKey= new \app\admin\model\member\MemberKey();
        $api_id = mt_rand(100000, 9999999);
        $app_secret = strtoupper(md5(uniqid()));
        $res = $MemberKey->where(['app_id' => $api_id])->find();
        if ($res) {
            get_app_id();
        } else {
            return ['app_id' => $api_id,'app_secret'=>$app_secret];
        }
    }

}



if (!function_exists('get_api_key')) {

    /**
     * 添加不重复API信息
     */

    function get_api_key()

    {
          $api_key = strtoupper(md5(uniqid()));
            return ['api_key' => $api_key];
    }

}


if (!function_exists('genUserNumber')) {


// 自动生成随机用户名
// 测试，循环创建1万个随机账号，0碰撞，10万大约0-3个碰撞，足够应付未来数十亿级PV
    function genUserNumber()
    {
        $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $username = "";

        $ChannelUsers= new \app\member\model\channel\ChannelUsers();

        $username=\think\helper\Str::random(6);

        $res = $ChannelUsers->where(['mid' => $username])->find();

        if ($res) {
            genUserNumber();
        } else {
            return $username;
        }

    }

}

if (!function_exists('get_device_type')) {

    function get_device_type()
    {
        //全部变成小写字母

        if(isset($_SERVER["HTTP_USER_AGENT"])){

            $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
            $type = $agent;
            //分别进行判断
            if (strpos($agent, 'iphone') || strpos($agent, 'ipad')) {
                $type = 'Ios';
            }

            if (strpos($agent, 'android')) {
                $type = 'Android';
            }
            if (strpos($agent, 'windows nt')) {
                $type = 'Web';
            }

        }else{
            $type = 'other';
        }



        return $type;
    }
}


if (!function_exists('makeApiSign')) {

    function makeApiSign($data, $md5Key)

    {
        ksort($data);
        reset($data);
        $arg = '';
        foreach ($data as $key => $val) {
            //空值不参与签名
            if ($val == '' || $key == 'sign') {

                continue;
            }
            $arg .= ($key . '=' . $val . '&');

        }
        $arg = $arg . 'key=' . $md5Key;

        //签名数据转换为大写
        $sig_data = strtoupper(md5($arg));

        //返回签名

        return $sig_data;

    }

}



if (!function_exists('verifyApiSign')) {

    function verifyApiSign($data, $md5Key)

    {


        ksort($data);
        reset($data);

        $arg = '';

        foreach ($data as $key => $val) {

            //空值不参与签名

            if ($val == '' || $key == 'sign') {

                continue;

            }

            $arg .= ($key . '=' . $val . '&');

        }

        $arg = $arg . 'key=' . $md5Key;

        $signData = strtoupper(md5($arg));

        if ($signData == $data['sign']) {

            return true;

        }

        return false;

    }

}


/**
 * CURL请求
 * @param $url string 请求url地址
 * @param $method string 请求方法 get post
 * @param $Proxy string 增加代理
 * @param mixed $postfields post数据数组
 * @param array $headers 请求header信息
 * @param bool|false $debug  调试开启 默认false
 * @return mixed
 */
function httpRequest($url, $method="GET", $postfields = null, $headers = array(),$proxy=false,$debug = false)
{


    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */


    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 10); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        case 'GET':


        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }



       if(!empty($proxy)){
         curl_setopt ($ci, CURLOPT_PROXY, GetProxy());
       };

    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if ($ssl) {
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        var_dump($requestinfo);
        echo "=====response=====\r\n";
        var_dump($response);
    }
    curl_close($ci);
    return  $response ;
    //return array($http_code, $response,$requestinfo);
}
function UpdateProxy(){


    $config=new \app\admin\model\admin\Config();
    $url= $config->where('name','proxy')->value('value');
    $res=httpRequest($url);
    $ress=json_decode($res,true);
    if($ress['code']==0){
        $ip=$ress['data'][0]['ip'];
        $port=$ress['data'][0]['port'];
        $proxy=$ip.':'.$port;
        $config->where('name','proxy_ip')->save(['value'=>$proxy]);
    }else{
        $proxy="";
    }
    return $proxy;

}


if (!function_exists('GetProxy')) {


    function GetProxy()

    {

        $config=new \app\admin\model\admin\Config();
        return $config->where('name','proxy_ip')->value('value');

    }
}


if (!function_exists('validate_google_code')) {

    /**

     * 验证google验证码

     * @param $secret

     * @param $code

     */

    function validate_google_code($secret, $code)

    {

        $ga = new \extend\google\GoogleAuthenticator();

        return $ga->verifyCode($secret, $code, 2);

    }

}

function getDataByCurl($url,$HEADER=array()) {

    $ch = curl_init ();

    curl_setopt($ch,CURLOPT_URL,$url);

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($ch, CURLOPT_POST, false);

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);

    curl_setopt($ch, CURLOPT_TIMEOUT, 60);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch,CURLOPT_HTTPHEADER,$HEADER);

    $return = curl_exec($ch);

    curl_close($ch);

    return $return;

}


if (!function_exists('redisLocker')) {

    function redisLocker()

    {

        static $obj = null;

        if (is_null($obj)) {

            $obj = new \redis\RedisLock(config('redis.lock_server'));

        }

        return $obj;

    }

}


/****
 * @inheritDoc 随机获取订单号
 * @return string
 */
if (!function_exists('getRandOrderSn')) {
    function getRandOrderSn($prefix='pt'): string
    {

        return $prefix.'_' . date('YmdHis') . rand(100001, 998999);

    }
}

/***
 * @param $order_sn
 * @return bool
 */

 function insCheckRedis($order_sn)

{

    //连接本地的Redis 服务

    $redis = new \Redis();

    $redis->connect('127.0.0.1', 6379);
    $check = $redis->sIsMember('order', $order_sn);
    if (!$check) {
        //向Redis的send_captcha队列投递数据
        $isPush = $redis->sADD('order', $order_sn);

        if (!$isPush) {

            return false;

        }

        return true;

    } else {

        return false;

    }

}


/***
 * @param $order_sn
 * @return bool
 */

function preCheckRedis($order_sn)

{

    //连接本地的Redis 服务

    $redis = new \Redis();

    $redis->connect('127.0.0.1', 6379);
    $check = $redis->sIsMember('pre_ck', $order_sn);
    if (!$check) {

        //向Redis的send_captcha队列投递数据




        $isPush = $redis->sADD('pre_ck', $order_sn);

        if (!$isPush) {

            return false;

        }

        return true;

    } else {

        return false;

    }

}




function getIP(){



    if (getenv("HTTP_CLIENT_IP"))

        $ip = getenv("HTTP_CLIENT_IP");

    else if(getenv("HTTP_X_FORWARDED_FOR"))

        $ip = getenv("HTTP_X_FORWARDED_FOR");

    else if(getenv("REMOTE_ADDR"))

        $ip = getenv("REMOTE_ADDR");else$ip = "Unknow";

    return $ip;

 }

function numFormat($num) {

    return is_numeric($num) ? sprintf("%.2f", substr(sprintf("%.3f", $num), 0, -1)) : '';
}

function amountFormat($amount)
{
 return   bcadd($amount, "0", 2);
}
function getRandomString($len, $chars=null)

{
    if (is_null($chars)){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    }
    mt_srand(10000000*(double)microtime());

    for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
        $str .= $chars[mt_rand(0, $lc)];

    }
    return $str;
}
// /**
//  *产生随机小数的函数
//  */
function randomFloat($min, $max) {
    return $min + mt_rand() / mt_getrandmax() * ($max - $min);
}

 function checkPer()
{

    $roleId=session('role_id');
    $role_info=Roles::where(['id'=>$roleId])->find();
    if($role_info['type']==1){
        return true;
    }

    $right=RolePermissions::where('role_id', $roleId)->find();
    $list=Permissions::whereIn('id',$right->right_list)->select();
    $code=[];
    foreach ($list as $k=>$v){
        foreach ($v['code'] as $k1=>$v1){
            $code[]=$v1;
        }
    }
    $controller=\request()->controller();
    $action=\request()->action();

    $checkAction=$controller.'@'.$action;

    if(in_array($checkAction,$code)){
        return true;
    }else{
        return false;
    }

}